<script setup lang="ts">
import {computed, onMounted, ref} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {fetchProductData} from "@/router/api.js";
import {useUserStore} from "@/stores/userStore.js";
import {ShoppingCart} from "@element-plus/icons-vue";
import {useCartStore} from "@/stores/cartStore";
import router from "@/router";
import {authUtilStore} from "@/utils/authStore";
import {ElMessage} from "element-plus";
import {useOrderStore} from "@/stores/orderStore";

const {addToCart} = useCartStore()
const {setTempOrderItems}=useOrderStore()
const cartStore = useCartStore()
const authStore = authUtilStore();
const isLogin = computed(() => useUserStore().isLogin);
const userInfo = useUserStore().userInfo;
//退出登录
const logout = () => {
  useUserStore().logout();
};
const route = useRoute();
const product = ref(null);
onMounted(async () => {
  await getProductData()
});

const num = ref(1);
// 获取产品数据
const getProductData = async () => {
  const productId = route.params.id;
  try {
    product.value = await fetchProductData(productId);
  } catch (error) {
    console.error('获取产品数据失败', error);
  }
}
const buyNow = (product: any, quantity: number) => {
  console.log(product, quantity);
  if (userInfo.status==='0'){
    ElMessage.warning('你已被冻结，无法购买');
    return;
  }

  if (userInfo && userInfo.id) {
    const goodid=product.id
    console.log(goodid)
    // 将商品存入临时订单
    setTempOrderItems(product, quantity,goodid)
    authStore.active = 1
    router.push('/orderPublic?type=buyNow') // 添加路由参数区分来源
  } else {
    alert('请先登录！')
  }
}
//跳转到购物车
const handleCart = () => {
  if (userInfo && userInfo.id) {
    authStore.active = 0;
    router.push('/orderPublic');
  } else {
    alert('请先登录！')
  }
};
const handAddToCart = (product: any, quantity: number) => {
  console.log(product, quantity);
  if (userInfo.status==='0'){
    ElMessage.warning('你已被冻结，无法购买');
    return;
  }

  if (userInfo && userInfo.id) {
    addToCart(product, quantity);
    ElMessage.success('添加成功');
  } else {
    alert('请先登录！')
  }
}

// 切换登录/注册状态
const handleAuthSwitch = (mode: 'login' | 'register') => {
  // 1. 切换登录/注册状态
  if (mode === 'login') {
    authStore.switchToLogin();
  } else {
    authStore.switchToRegister();
  }

  // 2. 导航到目标路由（无刷新）
  router.replace('/login-register');
};
</script>

<template>
  <div class="container">
    <!-- Header -->
    <div class="header">
      <h1 class="logo">嗨购网上商城</h1>
      <div style="width: 40%;height: 100%">
        <ul class="shortcut">
          <li><a href="">我的账户</a></li>
          <li><a href="">我的订单</a></li>
          <li><a href="">使用帮助</a></li>
        </ul>
        <p class="logoInfo">
        <span style="display: flex;align-items: center;" v-if="isLogin">
          <el-avatar size="15" :src="userInfo.avatar"
                     style="margin-right: 10px;border: 1px solid #ccc;"/>
          <button @click="logout">退出</button>
        </span>
          <span class="login-register-links" v-if="!isLogin">
          [<a href="#" @click.prevent="handleAuthSwitch('login')">登录</a>
           <a href="#" @click.prevent="handleAuthSwitch('register')">注册</a>]
          </span>
        </p>
      </div>
    </div>
    <!-- Content -->
    <div class="content">
      <!-- top -->
      <div class="content-top">
        <a href="/" class="title">首页</a>
        <div>|</div>
        <div class="link">商品详情</div>
        <div class="cart-container" @click="handleCart">
          <el-icon class="cart-icon">
            <ShoppingCart/>
          </el-icon>
          <el-badge v-if="cartStore.cartStore.length>0" :value="cartStore.cartStore.length" :offset="[4, -5]">
            <span class="cart-text">购物车</span>
          </el-badge>
          <span v-else class="cart-text">购物车</span>
        </div>
      </div>
      <div v-if="product" class="content-main">
        <div class="product-detail">
          <div>
            <img :src="product.image" alt="产品图片"
                 style="width: 100%; max-width: 300px; aspect-ratio: 4/4;"/>
            <h2>{{ product.name }}</h2>
            <!-- 这里要判断是不是热卖或者最新上架 -->
            <p>热卖商品</p>
            <p>最新上架</p>
            <p>介绍：{{ product.description }}</p>
          </div>
        </div>
        <div class="product-detail-right">
          <p style="color:#e81414;">惊喜价：¥{{ product.sale_price }}</p>
          <p>市场价：¥<s>{{ product.market_price }}</s></p>
          <p>库存：{{ product.stock }}</p>
          <p>商品编码：1111111</p>
          <p>
            购买数量：
            <!--自行替换num，这里只是演示-->
            <el-input-number v-model="num" :min="1" size="default"/>
          </p>
          <el-button :disabled="product.stock < num||product.stock === 0" @click="buyNow(product, num)" color="#e81414" size="large">
            立即购买
          </el-button>
          <el-button :disabled="product.stock < num||product.stock === 0" @click="handAddToCart(product ,num)"
                     type="primary" size="large" :icon="ShoppingCart">加入购物车
          </el-button>
        </div>
      </div>
      <div v-else>
        <p>加载中...</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.cart-container {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  border-radius: 20px;
  background: bisque;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  cursor: pointer;
  font-size: 16px;
  gap: 8px;
  position: fixed; /* 固定定位 */
  right: 40px; /* 距离右边的距离 */
}

.cart-icon {
  font-size: 25px;
  color: orange;
}

.cart-text {
  font-weight: bold;
  color: #303133;
  margin-left: 4px;
}

.cart-container:hover {
  background: #c0e3ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.cart-container:active {
  transform: translateY(0);
}

.product-detail-right p {
  margin: 20px 0;
  font-size: 20px;
}

.product-detail-right {
  width: 60%;
  height: 100%;
}

.product-detail {
  width: 35%;
  height: 100%;
}

.content-main {
  margin-top: 20px;
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  height: 550px;
  overflow: hidden;
}

.link {
  font-weight: bold;
  margin-left: 500px;
}

.title {
  color: white;
  text-decoration: none;
  margin-left: 100px;
  margin-right: 20px;
}

.title:hover {
  text-decoration: underline;
  cursor: pointer;
  color: blue;
}

.content-top {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  color: white;
  font-size: 23px;
  background-color: #e89777;
  padding: 10px 0;
}

.content {
  width: 100%;
}

.header {
  display: flex;
  flex-direction: row;
  width: 100%;
}

.logo {
  padding-left: 30px;
  width: 60%;
  color: orange;
  line-height: 60px;
  font-weight: 500;
  font-style: italic;
  letter-spacing: 5px;
}

.shortcut {
  display: flex;
  list-style: none;
  justify-content: right;
  margin-right: 20px;
}

.shortcut li {
  margin-left: 15px;
}

.shortcut a {
  text-decoration: none;
  color: #666;
}

.logoInfo {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: right;
  padding-right: 20px;
}

.login-register-links {
  margin-left: 15px;
}

.login-register-links a {
  color: #e17d58;
  text-decoration: none;
  margin: 0 5px;
}

.container {
  width: 100%;
  height: 100vh;
  overflow: hidden;
}
</style>
